extends ItemAppender


class_name ReparentItemAppender
"""
重置节点父节点的追加器
"""


## 挂载子节点入口
@export var entry: Node = null
## 需要恢复的属性(部分字段挂载后会变更,如:position,rotation)
@export var recover_properties: Array[String] = ["position", "rotation", "scale"]
@export var is_deferred: bool = false


var item_map: Dictionary[Node, Node] = {}
var property_map: Dictionary[Node, Dictionary] = {}


func store(node: Node) -> void:
    if recover_properties.size() < 1:
        return
    var dict: Dictionary = {}
    for p in recover_properties:
        var v: Variant = node.get(p)
        if v != null:
            dict[p] = v
    property_map[node] = dict

func recover(node: Node) -> void:
    if recover_properties.size() < 1:
        return
    var dict: Dictionary = property_map[node]
    for p in dict:
        if is_deferred:
            node.set_deferred(p, dict[p])
        else:
            node.set(p, dict[p])

func append(node: Node) -> void:
    var parent: Node = node.get_parent()
    var entry_parent: Node = item_container if not entry else entry
    item_map[node] = parent
    if parent != entry_parent:
        store(node)
        NodeHelper.reparent(node, entry_parent, is_deferred)
        recover(node)

func remove(node: Node) -> void:
    var parent: Node = item_map[node]
    var entry_parent: Node = item_container if not entry else entry
    if parent != entry_parent:
        if is_deferred:
            node.call_deferred("reparent", parent)
        else:
            node.reparent(parent)
        NodeHelper.reparent(node, parent, is_deferred)
        recover(node)
    item_map.erase(node)
